﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OF.Utility;
using YouWei.Infrastructure.Dto;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Models;
using YouWei.Utility;
using YouWei.Utility.Logging;

namespace YouWei.Infrastructure.Service
{
    public class ExternalInterfaceService
    {
        private static string ApiCheLeXingUrl => AppSettings.ApiCheLeXingUrl;
        private static string ApiCheLeXingKey => AppSettings.ApiCheLeXingKey;

        private static Encoding pEncoding = Encoding.UTF8;


    


        /// <summary>
        /// 获取车乐行-行驶证接口信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static ApiCheLeXingToDisplayResponse<ResCheLeXingVehicle> GetCheLeXingVehicleInfo(ReqCheLeXingVehicle request)
        {
            string szResult = "";
            var sv = new InterfaceDataVehicleService();
            //有缓存数据直接返回
            var oLocal = GetLocalRecord(request.hpzl, request.hphm);
            if (oLocal != null)
            {
                var oResultData=new ResCheLeXingVehicle();
                oLocal.MergeTo(oResultData);
                return new ApiCheLeXingToDisplayResponse<ResCheLeXingVehicle>
                {
                    code = 1,
                    msg = string.Empty,
                    data = oResultData
                };
            }
            var result = new ApiCheLeXingToDisplayResponse<ResCheLeXingVehicle>();
            ApiCheLeXingResponse <ResCheLeXingVehicle> oData = GetCheLeXingVehicle(request, out szResult);
            var nTriedTimes = 3;
            var nAlearyTriesTimes = 1;
            while (oData == null && nTriedTimes>0)
            {
                Thread.Sleep(2500);
                oData = GetCheLeXingVehicle(request, out szResult);
                nTriedTimes--;
                nAlearyTriesTimes++;
            }
            if (oData == null)
            {
                result.code = 0;
                result.msg = "查询失败，错误原因：超时未查出";

                Log4netLog.Error(102,"车乐行行驶证接口查询失败，错误原因：查询3次未查出,请求数据为："+request.ToJSON());
            }
            else if ((oData.code != "201" && oData.code != "888"))
            {
                result.code = 0;
                result.msg = "查询失败，错误原因：外部接口出错";

                Log4netLog.Error(102, "车乐行行驶证接口查询失败，错误原因：车乐行接口返回查询错误,请求数据为：" + request.ToJSON() + ",错误信息为：" + oData.msg);
            }
            else
            {
                result.code = 1;
                result.msg = "查询成功！！！";
                result.data = oData.data;
               
                var oInfo=new InterfaceDataVehicle();
                result.data.MergeTo(oInfo);
                oInfo.clxh = result.data.clxhText;
                oInfo.TryTimes = nAlearyTriesTimes;
                oInfo.CreatedTime = DateTime.Now;
                sv.Insert(oInfo);
            }

            
            return result;
        }

        private static InterfaceDataVehicle GetLocalRecord(string hpzl,string hphm)
        {
            InterfaceDataVehicle oInfo = null;
            var sv = new InterfaceDataVehicleService();
            oInfo=sv.GetLocalSuccessRecord(hpzl, hphm, DateTime.Now.AddMinutes(-AppSettings.CheLeXingDataCacheTime));

            return oInfo;
        }
        /// <summary>
        /// 获取车乐行-行驶证接口
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <returns>null，代表接口请求失败，非null代表接口请求成功</returns>
        private static ApiCheLeXingResponse<ResCheLeXingVehicle> GetCheLeXingVehicle(ReqCheLeXingVehicle request, out string szResult)
        {
            ApiCheLeXingResponse<ResCheLeXingVehicle> oReturn = null;
            szResult = "";
            string szTpl = "{0}/cxy/1004?api_key={1}&hpzl={2}&hphm={3}";
            var szUrl = string.Format(szTpl
                                        , ApiCheLeXingUrl
                                        , ApiCheLeXingKey
                                        , request.hpzl
                                        , request.hphm
                                    
                                        );
            if (!string.IsNullOrEmpty(request.syr))
            {
                szUrl += $"&syr={request.syr}";
            }
            var szContent = "";
            if (RequestHelper.GetHtml(szUrl, "get", pEncoding, out szContent))
            {
                //szResult = szContent;

                try
                {
                    var oRes = szContent.JSONToObject<ApiCheLeXingResponse<ResCheLeXingVehicle1>>();
                    if (oRes != null)
                    {
                        oReturn = new ApiCheLeXingResponse<ResCheLeXingVehicle>();
                        oReturn.code = oRes.code;
                        oReturn.msg = oRes.msg;
                        oReturn.data = oRes.data;
                    }
                }
                catch (Exception ex)
                {
                    var oRes = szContent.JSONToObject<ApiCheLeXingResponse<ResCheLeXingVehicle2>>();
                    if (oRes != null)
                    {
                       oReturn=new ApiCheLeXingResponse<ResCheLeXingVehicle>();
                        oReturn.code = oRes.code;
                        oReturn.msg = oRes.msg;
                        oReturn.data = oRes.data;
                    }
                }

            }
            return oReturn;
        }


    }






}
